import React, {Component} from 'react';
import {View, StyleSheet, Text, ListView, TouchableOpacity,RefreshControl, Platform,Image,ActivityIndicator, Modal,BackAndroid,TouchableWithoutFeedback,
    TouchableHighlight,TextInput, ScrollView} from  'react-native';
import EasyList from 'react-native-easy-listview-gridview';
import Icon from 'react-native-vector-icons/FontAwesome';
import Button from 'react-native-button';
import GoodDetail from './GoodDetail';
import {LinesLoader} from 'react-native-indicator';
let dimension = require('Dimensions');
let {width, height} = dimension.get('window');
let that;
let collect = require('../../img/collect.png');
import Mock from 'mockjs';
export default class ClassificationDetailView extends Component{
    constructor(props) {
        super(props);
        this.state={
            goodInfo:{"goodName": "",
                "goodPriceInfo": "",
                "goodPrice": [
                    {
                        "price": 0,
                        "unit": ""
                    }
                ],
                "goodimage": "http://dummyimage.com/300x300/e43b12)"},
            modalVisible:false,
            buttonSelect1:false,
            buttonSelect2:false,
            count:1,
            money:0.00,
            goodId:null,
            selectId:0
        };
        that=this;
        this._onFetch = this._onFetch.bind(this);
        this.back=this.back.bind(this);
        this.renderHeaderView=this.renderHeaderView.bind(this);
        that._focus1=that._focus1.bind(this);
        this._closeModal=this._closeModal.bind(this);
        this.click=this.click.bind(this);
        this._changeCount=this._changeCount.bind(this);
        this.unitView=this.unitView.bind(this)
    }

    componentWillMount () {
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', this.back);
        }
    }

    componentWillUnmount(){
        if (Platform.OS === 'android') {
            BackAndroid.removeEventListener('hardwareBackPress', this.back);
        }
    }
    back(){
        this.props.navigation.goBack();
        return true;
    }

    render(){
        return(
            <View style={styles.container}>
                <EasyList
                    renderHeader={this.renderHeaderView}
                    ref={component => this.listview = component}
                    renderItem={this.renderRow}
                    column={2}
                    dataSizePerPage={20}
                    refreshHandler={this._onFetch}
                    loadMoreHandler={this._onFetch}
                    renderFooterNoMore={this.renderFooterNoMore}
                    renderFooterError={this.renderFooterError}
                    renderFooterLoading={this.renderFooterLoading}
                />
                <Modal
                    animationType="none"
                    visible={this.state.modalVisible}
                    onRequestClose={that._closeModal}
                    transparent={true}
                >
                    <View style={{backgroundColor:'rgba(0,0,0,0.8)',width:width,height:height}}>
                        <TouchableWithoutFeedback onPress={that._closeModal}>
                            <View  style={{width:width,height:height/2}}>
                            </View>
                        </TouchableWithoutFeedback>
                        <ScrollView style={{backgroundColor:'white',width:width,height:height/2}}>
                            <View style={{flexDirection:'row',borderBottomWidth:0.5,borderColor:'#888888',padding:10}}>
                                <Image source={{uri:this.state.goodInfo.goodimage}} style={{width:50,height:50}}/>
                                <View style={{marginLeft:20}}>
                                    <Text style={{fontSize:20,fontWeight:'bold'}}>{this.state.goodInfo.goodName}</Text>
                                    <Text style={{fontSize:16,color: 'red'}}>{this.state.goodInfo.goodPriceInfo}</Text>
                                </View>
                            </View>
                            <View style={{borderBottomWidth:0.5,borderColor:'#888888',padding:10,flexDirection:'row',justifyContent:'space-between',alignItems:'center'}} >
                                <Text style={{fontSize:20}}>单位:</Text>
                                <View style={{flexDirection:'row'}}>
                                    {
                                        this.state.goodInfo==={}?
                                            null:this.unitView()
                                    }
                                </View>
                            </View>
                            <View style={{borderBottomWidth:0.5,borderColor:'#888888',padding:10,justifyContent:'space-between',flexDirection:'row',alignItems:'center'}}>
                                <Text style={{fontSize:20}}>数量：</Text>
                                <View style={{flexDirection:'row',borderRadius:8,borderWidth:0.5,alignItems:'center',padding:0}}>
                                    <Button style={{fontSize:20,width:30}} isDisabled={true}
                                            onPress={()=>this._changeCount(false)}>-</Button>
                                    <TextInput style={styles.textInputStyle}
                                               underlineColorAndroid="transparent">{this.state.count}</TextInput>
                                    <Button style={{fontSize:20,width:30}} isDisabled={false}
                                            onPress={()=>this._changeCount(true)}>+</Button>
                                </View>
                            </View>
                            <View style={{borderBottomWidth:0.5,borderColor:'#888888',padding:10,justifyContent:'space-between',flexDirection:'row',alignItems:'center'}}>
                                <Text style={{fontSize:20}}>总额：</Text>
                                <Text style={{color:'#585858'}}>{this.state.money}元</Text>
                            </View>
                            <TouchableOpacity style={{position: 'absolute',right:10,top:10,}} onPress={that._closeModal}>
                                <Icon name="close" size={18} color="#000000"/>
                            </TouchableOpacity>
                        </ScrollView>
                    </View>
                    <View style={{position: 'absolute',bottom:0,flexDirection:'row',justifyContent:'space-between',width:width,alignItems:'center'}}>
                        <Button style={{width:width/2,backgroundColor:'green',padding:10,color:'white'}}>加入购物车</Button>
                        <Button style={{width:width/2,backgroundColor:'red',padding:10,color:'white'}}>立即购买</Button>
                    </View>
                </Modal>
            </View>
        )
    }

    unitView(){
        if (this.state.goodInfo==={})
        {
            return;
        }
        else {
            let itemArr = [];
            for (let i = 0; i < this.state.goodInfo.goodPrice.length; i++) {
                    itemArr.push(
                        <Button key={i} style={this.state.selectId==i?{marginLeft:10,borderWidth:1,backgroundColor:'blue'}:{marginLeft:10,borderWidth:1,backgroundColor:'white'}}
                                onPress={(i)=>this.clickUnit(i)}>{this.state.goodInfo.goodPrice[i].unit}</Button>
                    )

            }
            return itemArr;
        }
    }
    _changeCount(isAdd){
        let count1=this.state.count;
        if (isAdd){
            this.setState({count:++count1})
        }
        else {
            if (count1==1){
                return
            }
            this.setState({count:--count1})
        }
    }
    click(isMain){
        if (isMain) {
            this.setState({
                buttonSelect1: true,
                buttonSelect2: false
            })
        }
        else{
            this.setState({
                buttonSelect2:true,
                buttonSelect1:false
            })
        }
    }

    _focus1(){
        this._setModalVisible(true);
        let str="http://rapapi.org/mockjs/18259/api/getSimple?id=485454";
        fetch(str)
            .then((response) => response.json())
            .then((responseData) => {
                let data = Mock.mock(responseData);
                if (data.success) {
                    let goodinfo = data.data;
                    this.setState({goodInfo:goodinfo})
                }
            })
            .catch((error) => {
              alert("网络异常")
            });
    }
    _closeModal(){
        this._setModalVisible(false)
    }
    _setModalVisible(isVisible){
        this.setState({
            modalVisible:isVisible
        })
    }
    _onFetch(pageNo, success, failure) {
        //方便测试空数据情况
        // setTimeout(()=> {
            if (pageNo === 3) {
                success([]);
                return;
            }
            fetch(this.props.api_url)
                .then((response) => response.json())
                .then((responseData) => {
                    let data = Mock.mock(responseData);
                    if (data.success) {
                        let items = data.data;
                        success(items)
                    }
                })
                .catch((error) => {
                    failure('加载失败', null)
                });
        // },1000)
    }

    renderHeaderView(){
        const { params } = this.props.navigation.state;
        let imageSource;
        switch (params.type){
            case '啤酒':imageSource=require('../../img/classification/beer.png');break;
            case '白酒':imageSource=require('../../img/classification/white_wine.png');break;
            case '红酒':imageSource=require('../../img/classification/red_wine.png');break;
            case '饮料':imageSource=require('../../img/classification/drink.png');break;
            case '洋酒':imageSource=require('../../img/classification/wine.png');break;
            default:imageSource=null;

        }
        return(
            <Image source={imageSource} style={{width:width,height:width/2}}/>
        )
    }

    renderRow(index,rowData){
        let viewMarginLeft;
        let viewMarginRight;
        let viewMarginTop=1;
        let viewMarginBottom=1;
        let url='https://h5.youzan.com/v2/goods/3nhu8ptov31m2?reft=1496974798633&spm=f44930604';
        if (index%2==1){
            viewMarginRight = 2;
            viewMarginLeft = 1;
        }
        else {
            viewMarginLeft = 2;
            viewMarginRight = 1;
        }
        return (
            <View style={[styles.listViewStyle,{marginLeft:viewMarginLeft,marginRight:viewMarginRight,marginTop:viewMarginTop,marginBottom:viewMarginBottom}]} key={index}>
                <TouchableOpacity style={{flex:1}} onPress={(componentName,param)=>that._press('GoodDetail',{title:rowData.goodsName})} >
                    <Image resizeMode='stretch' source={{uri:rowData.goodsImage}} style={styles.imageStyle}/>
                    <Text style={{fontSize:16}}>{rowData.goodsName}</Text>
                    <View style={{justifyContent:'space-between',flexDirection:'row'}}>
                        <Text style={{fontSize:14,color: 'red'}}>{rowData.goodsPrice}</Text>
                        <TouchableOpacity style={{backgroundColor:'#FF8C00',padding:2}} onPress={that._focus1}>
                            <Text style={{fontSize:11,color:'#585858'}}>订购</Text>
                        </TouchableOpacity>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
    //EasyGridView底部视图
    //当没有更多数据的时候
    renderFooterNoMore(){
        return(
            <View style={{paddingBottom:70,paddingTop:20}}>
                <Text style={{ textAlign:'center'}}>没有更多了</Text>
            </View>
        )
    }
    //当加载出错的时候
    renderFooterError(){
        return(
            <View style={{paddingBottom:70,paddingTop:20}}>
                <Text style={{ textAlign:'center'}}>加载出错</Text>
            </View>
        )
    }
    //当正在加载的时候
    renderFooterLoading(){
        return(
            <View style={{paddingBottom:70,paddingTop:20,flexDirection:'row',justifyContent:'center',alignItems: 'center'}}>
                <LinesLoader size={10}/>
                <Text style={{ textAlign:'center'}}>正在加载</Text>
            </View>
        )
    }

    _press(componentName,param) {
        const { params } = this.props.navigation.state;
        if (params.fun == null) return;
        params.fun(componentName,param);
    }

    clickUnit(id){
        this.setState({selectId:id})
    }

    static navigationOptions = ({navigation}) => ({
        title: navigation.state.params.type,
    });
}
ClassificationDetailView.propTypes = {
    api_url: React.PropTypes.string,
    param:React.PropTypes.object
};
ClassificationDetailView.defaultProps = {
    api_url: 'http://rapapi.org/mockjs/18259/api/getYouLike?userId=456',
    param:null
};
const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#D8D8D8'
    },
    leftViewStyle: {
        // 绝对定位
        // position: 'absolute',
        // left: 10,
        // top: Platform.OS == 'ios' ? 24 : 10,
        flexDirection:"row",
        alignItems:'center',
        justifyContent:'center'
    },
    navOutViewStyle: {
        height: Platform.OS == 'ios' ? 64 : 44,
        backgroundColor: 'rgba(255,96,0,1.0)',

        // 设置主轴的方向
        flexDirection: 'row',
        // 垂直居中 ---> 设置侧轴的对齐方式
        alignItems: 'center',
        // 主轴方向居中
        justifyContent: 'space-between'
    },
    imageStyle: {
        width: (width-26)/2,
        height: (width-26)/2
    },
    listViewStyle: {
        backgroundColor: 'white',
        borderBottomColor: '#e8e8e8',
        borderBottomWidth: 0.5,
        overflow:'hidden',
        padding:5
    },

    textInfo:{
        position: 'absolute',
        left: 5,
        top: 5,
        backgroundColor: 'red',
        color: 'white',
        padding: 2,
    },
    textInputStyle:{
        borderColor:'#484848',
        borderRightWidth:0.5,
        borderLeftWidth:0.5,
        // height:20,
        fontSize:15,
        padding:0,
        textAlign:'center',
        width:30
    }
});